﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

namespace SmartProject.Entity
{
    public class Attachment : EntityBase
    {
        public virtual User Creator { get; set; }

        public virtual byte[] Content { get; set; }

        public virtual string Filename { get; set; }

        public virtual FileType Type { get; set; }

        /// <summary>
        /// Gets or sets the task associated with this Attachment.
        /// </summary>
        public virtual Task Task { get; set; }

        /// <summary>
        /// Adds a new attachment that belongs to a user.
        /// </summary>
        /// <param name="session">Session used in this request.</param>
        /// <param name="owner">Owner username.</param>
        /// <param name="content">Byte array containing the content.</param>
        /// <param name="filename">Name of the file to save.</param>
        /// <returns>Attachment.</returns>
        public static Attachment NewAttachment(ISession session, string owner, byte[] content, string filename)
        {
            Attachment attachment = new Attachment();
            attachment.Creator = User.GetUserByUsername(session, owner);
            attachment.Content = content;
            attachment.Filename = filename;
            attachment.Type = FileType.GetFileTypeByFileName(session, filename);
            attachment.Save(session);

            return attachment;
        }

        /// <summary>
        /// Adds a new attachment that belongs to a user.
        /// </summary>
        /// <param name="session">Session used in this request.</param>
        /// <param name="ownerId">Owner Id.</param>
        /// <param name="content">Byte array containing the content.</param>
        /// <param name="filename">Name of the file to save.</param>
        /// <returns>Attachment.</returns>
        public static Attachment NewAttachment(ISession session, int ownerId, byte[] content, string filename)
        {
            Attachment attachment = new Attachment();
            attachment.Creator = User.GetUser(session, ownerId);
            attachment.Content = content;
            attachment.Filename = filename;
            attachment.Type = FileType.GetFileTypeByFileName(session, filename);
            attachment.Save(session);

            return attachment;
        }

        /// <summary>
        /// Gets an attachment by Id.
        /// </summary>
        /// <param name="session">Session used in this request.</param>
        /// <param name="id">Id of the attachment.</param>
        /// <returns>Attachment.</returns>
        public static Attachment GetAttachment(ISession session, int id)
        {
            return (Attachment)EntityBase.GetEntity(session, id, typeof(Attachment));
        }
    }
}
